<template>
	<div class="visitor-detail">
        <div class="dormitory-branch">
            <router-link to="/dormitory#record">访客记录</router-link>
            <span>&gt;</span>
            <span>访客详情</span>
        </div>

        <div class="zh-dormitory-tab" v-loading="loading.status" :element-loading-text="loading.txt">
            <div class="zh-list-title">
                <p>{{itemDetail.name}}</p>
                <p>[{{getTime(itemDetail.start_time)}} ~ {{getTime(itemDetail.end_time)}}]</p>
            </div>

			<div class="zh-tab-title">
                <span
                    v-if="itemDetail.picture_status == 1"
                    :class="activeapanel === 'image' ? 'is-active' : ''"
                    @click="changePanel('image')">
                    <i class="el-icon-picture"></i>图片</span>
				<span 
                    v-if="itemDetail.text_status == 1"
                    :class="activeapanel === 'table' ? 'is-active' : ''" 
                    @click="changePanel('table')">
                    <img :src="tableIcon">表格</span>
			</div>

			<div class="zh-t-list">
                <div v-show="activeapanel === 'image' ? true : false">
                    <div class="list-item">
                        <div class="item-img" v-for="(item, inx) in listImageData" :key="inx">
                            <img :src="BASE_URL + item.picture" @click="checkImg(item)">
                        </div>
                    </div>
                </div>

                <div v-show="activeapanel === 'table' ? true : false">
                    <div class="zh-dormitory-table">
                        <div class="export-excel">
                            <el-button type="primary" @click="getAllData">导出Excel</el-button>
                        </div>
                        <div class="zh-table-contents">
                            <el-table
                                :data="listTableData"
                                fixed
                                border
                                max-height="600"
                                style="width: 100%">
                                <el-table-column
                                    prop="respondents"
                                    label="姓名"
                                    align="center"
                                    show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column
                                    prop="start_time"
                                    label="来访时间"
                                    align="center"
                                    show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column
                                    prop="telphone"
                                    label="联系电话"
                                    align="center"
                                    show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column
                                    prop="id_number"
                                    label="身份证号"
                                    align="center"
                                    show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column
                                    prop="dormitory"
                                    label="拜访寝室"
                                    align="center"
                                    show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column
                                    prop="visitor"
                                    label="拜访人"
                                    align="center"
                                    show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column
                                    prop="cause"
                                    label="事由"
                                    align="center"
                                    show-overflow-tooltip>
                                    <template slot-scope="scope">
                                        {{scope.row.cause ? scope.row.cause : '-'}}
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="end_time"
                                    label="离开时间"
                                    align="center"
                                    show-overflow-tooltip>
                                </el-table-column>
                            </el-table>

                            <div class="pageBox" v-if="totalNumber > 10">
                                <el-pagination
                                    background
                                    layout="prev, pager, next"
                                    @current-change="setCurrentPage"
                                    :page-size="listParam.pageSize"
                                    :current-page="listParam.pageIndex"
                                    :total="totalNumber">
                                </el-pagination>
                            </div>
                        </div>
                    </div>
                </div>
			</div>
		</div>

        <el-dialog
            title="图片预览"
            class="picture-preview"
            :visible.sync="imgVisible"
            :close-on-click-modal="false">
            <div>
                <img :src="imgViewUrl">
            </div>
        </el-dialog>
    </div>
</template>

<script>
import XLSX from 'xlsx';
import FileSaver from 'file-saver';
import tableIcon1 from './../../../assets/images/dormitory/table.png';
import tableIcon2 from './../../../assets/images/dormitory/table-active.png';

export default {
    data() {
        return {
            imgVisible: false, // 图片预览
            totalNumber: 0, // 表格总数
            imgViewUrl: '', // 图片地址
            activeapanel: 'image', // 当前显示的页面
            tableIcon: tableIcon1, // 表格图片
            listTableData: [], // 表格列表
            listImageData: [], // 图片列表
            itemDetail: {}, 
            loading: { // loading 状态
                status: false,
                txt: '获取数据...'
            },
            listParam: {
                pageIndex: 1, // 分页当前页数
                pageSize: 10 // 每页数据数量
            },
        }
    },
    created() {
        this.getList();
    },
    computed: {
        getTime() {
            return (time) => {
                return time ? time.substr(0, 10) : '';
            }
        },
    },
    methods: {
        /**
         * 获取详情信息
         */
        getList() {
            let success = (res => {
                this.itemDetail = res.data;

                if (this.itemDetail.picture_status == 1) {
                    this.activeapanel = 'image';
                    this.getImageList();
                } else {
                    this.activeapanel = 'table';
                }

                if (this.itemDetail.text_status == 1) {
                    this.getTableList();
                }
            })

            this.$ajax.get('api/dormitory/dormitoryVisitor',{params: {id: this.$route.query.id}, func:{success: success}})
        },
        /**
         * 获取图片详情
         */
        getImageList() {
            this.loading.status = true;

            let success = (res => {
                this.loading.status = false;
                this.listImageData = res.data;
            })
            let params = {
                dormitory_visitor_id: this.$route.query.id
            }

            this.$ajax.get('api/dormitory/dormitoryVisitorPicture',{params: params, func:{success: success}})
        },
        /**
         * 获取表格详情
         */
        getTableList() {
            this.loading.status = true;

            let success = (res => {
                this.loading.status = false;
                this.listTableData = res.data.data;
                this.totalNumber = res.data.data_sum;
            })
            let params = {
                dormitory_visitor_id: this.$route.query.id,
                page_size: this.listParam.pageSize,
                page_index: this.listParam.pageIndex
            }

            this.$ajax.get('api/dormitory/dormitoryVisitorDetail',{params: params, func:{success: success}})
        },
        /**
         * 切换页面
         * @param {String} pannel 页面标识
         */
        changePanel(panel) {
            this.activeapanel = panel;

            if (panel === 'table') {
                this.tableIcon = tableIcon2;
            } else {
                this.tableIcon = tableIcon1;
            }
        },
        /**
         * 查看图片
         * @param {String} item 图片信息
         */
        checkImg(item) {
            this.imgVisible = true;
            this.imgViewUrl = this.BASE_URL + item.picture
        },
        /**
         * 获取全部数据后导出
         */
        async getAllData() {
            if (this.totalNumber <= this.listParam.pageSize) {
                this.exportExcel(this.listTableData);
            } else {
                let All = [];
                let len = Math.ceil(this.totalNumber / 100);
                let success = (res => {
                    All = [...All, ...res.data.data];
                })

                for (let i=1; i<=len; i++) {
                    let params = {
                        dormitory_visitor_id: this.$route.query.id,
                        page_index: i,
                        page_size: 100,
                    }

                    await this.$ajax.get('api/dormitory/dormitoryVisitorDetail', {params: params, func:{success: success}});
                }

                this.exportExcel(All);
            }
        },
        /**
         * 导出Excel表
         * @param {Array} allData 全部数据
         */
        exportExcel(allData) {       
            if(allData.length === 0){
                this.$message.warning("导出的数据为空！");
                return false;
            }
            
            let exportList = [];
            const defaultCellStyle =  { font: { name: "Verdana", sz: 14, color: "FF00FF88"}, fill: {fgColor: {rgb: "FFFFAA00"}}};
            const wopts = { bookType:'xlsx', bookSST:false, type:'binary', defaultCellStyle: defaultCellStyle, showGridLines: false};
            const wb = { SheetNames: ['Sheet1'], Sheets: {}, Props: {} };

            for (let i = 0; i <= allData.length - 1;  i++) {
                if(i===0){
                    this.live_name  =  allData[i].l_name
                }

                exportList.push({
                    "姓名": allData[i].respondents,
                    "来访时间": allData[i].start_time,
                    "联系电话": allData[i].telphone,
                    "身份证号": allData[i].id_number,
                    "拜访寝室": allData[i].dormitory,
                    "拜访人": allData[i].visitor,
                    "事由": allData[i].cause,
                    "离开时间": allData[i].end_time
                });
            }

            wb.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(exportList)
            wb.Sheets['Sheet1']["!cols"] = [{
                wpx: 140
            }, {
                wpx: 140
            }, {
                wpx: 140
            }, {
                wpx: 100
            }, {
                wpx: 180
            }, {
                wpx: 80
            }, {
                wpx: 100
            }, {
                wpx: 250
            }, {
                wpx: 140
            }];

            //创建二进制对象写入转换好的字节流
            let tmpDown =  new Blob([this.str2Buffer(XLSX.write(wb, wopts))], { type: "application/octet-stream" });
            FileSaver.saveAs(tmpDown, `访客记录-表格.xlsx`);
        },
        /**
         * 字符串转类型化数组
         * @param {String} str 字符串
         */
        str2Buffer(str) {
            if (typeof ArrayBuffer !== 'undefined') {
                let buf = new ArrayBuffer(str.length);
                let view = new Uint8Array(buf);

                for (let i = 0; i != str.length; i+=1){
                    view[i] = str.charCodeAt(i) & 0xFF;
                }
                return buf;
            } else {
                let buf = new Array(str.length);

                for (let i = 0; i != str.length; i+=1){
                    buf[i] = str.charCodeAt(i) & 0xFF;
                }
                return buf;
            }
        },
        /**
         * 设置列表的当前页数
         * @param {Number} val 页数
         */
        setCurrentPage(val) {
            this.listParam.pageIndex = val;

            this.getTableList();
        },
    },
}
</script>

<style lang="scss">
.visitor-detail {
    margin: 20px auto 50px;
    max-width: 1200px;
    min-height: calc(100vh - 209px);

    .dormitory-branch {
        a {
            font-size: 14px;
            color: #333;
        }

        span:nth-child(2) {
            padding: 0 6px;
        }

        span {
            font-size: 14px;
            color: #666;
        }
    }

    .zh-dormitory-tab {
        margin-top: 20px;
        padding: 42px 60px 40px;
        background: #fff;
        box-shadow: 0 1px 1px 0 rgba(0,0,0,0.10);
    }

    .zh-list-title {
        position: relative;
        margin-bottom: 44px;
        text-align: center;

        >p:first-child {
            font-size: 20px;
            font-weight: bold;
        }

        >p:last-child {
            position: absolute;
            right: 0;
            top: 0;
            margin: 0;
            font-size: 12px;
            color: #666;
        }
    }

    .zh-tab-title {
        margin-bottom: 33px;
        font-size: 0;

        span {
            display: inline-block;
            width: 90px;
            height: 36px;
            line-height: 36px;
            text-align: center;
            font-size: 14px;
            color: #666666;
            box-sizing: border-box;
            cursor: pointer;

            i,
            img {
                margin-right: 4px;
                font-size: 18px;
                vertical-align: middle;
            }
        }

        span:first-child {
            border-top-left-radius: 4px;
            border-bottom-left-radius: 4px;
        }

        span:last-child {
            border-top-right-radius: 4px;
            border-bottom-right-radius: 4px;
        }

        .is-active {
            color: #348EFC;
        }
    }

    .list-item {
        display: flex;
        flex-wrap: wrap;

        .item-img {
            position: relative;
            margin-right: 20px;
            margin-bottom: 20px;
            width: 200px;
            height: 200px;
            text-align: center;
            box-sizing: border-box;
            cursor: pointer;

            img {
                width: 100%;
                height: 100%;
                object-fit: contain;
            }
        }

        .item-img:nth-child(5n) {
            margin-right: 0;
        }
    }

    .zh-dormitory-table {
        position: relative;
        
        .export-excel {
            position: absolute;
            top: -56px;
            right: 0;

            button {
                padding: 0;
                width: 86px;
                height: 32px;
                line-height: 32px;
            }
        }

        .el-table__header-wrapper {
            .el-table__header {
                thead {
                    tr th {
                        padding: 8px 0;
                        font-size: 14px;
                        color: #666;
                        background: #EFEFEF;
                    }
                }
            }
        }

        .el-table__body-wrapper {
            .el-table__body {
                .el-table__row {
                    td {
                        padding: 8px 0;
                    }
                }
            }
        }

        .pageBox {
            display: inline-block;
            margin-top: 20px;
            background: #fff;

            .el-pagination.is-background .btn-prev,
            .el-pagination.is-background .btn-next,
            .el-pagination.is-background .el-pager li {
                background: #fff;
            }

            .el-pagination.is-background .el-pager .active {
                background: #409EFF;
            }
        }
    }
    
    .picture-preview {
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0;

        .el-dialog {
            margin: 0;
            margin-top: 0 !important;
            width: 70vw;
            height: 70vh;
            max-width: 1200px;
            max-height: 900px;
            overflow: hidden;

            .el-dialog__header {
                padding: 0 0 0 20px;
                height: 36px;
                line-height: 36px;
                background: #348EFC;

                >span {
                    font-size: 14px;
                    color: #FFFFFF;
                }

                button {
                    top: 10px;

                    i {
                        color: #fff;
                    }
                }
            }

            .el-dialog__body {
                padding: 20px 0;
                width: 100%;
                height: calc(100% - 40px);
                box-sizing: border-box;

                div {
                    padding: 0 40px;
                    width: 100%;
                    height: 100%;
                    text-align: center;
                    overflow-y: auto;
                    box-sizing: border-box;

                    img {
                        max-width: 100%;
                    }
                }
            }
        }
    }
}
</style>